package com.wowangz.cms.systemmanage.city.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.city.pojo.City;
import com.wowangz.cms.systemmanage.city.service.CityService;
import com.wowangz.cms.systemmanage.province.pojo.Province;
import com.wowangz.cms.systemmanage.province.service.ProvinceService;

@Scope("prototype")
@Controller
public class CityController extends BaseController{

	private static Logger logger = LoggerFactory.getLogger(CityController.class);
	
	/**
	 * 点击菜单"市信息管理"显示“市信息管理”列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/city/queryCityList.web")
	public String queryProvinceList(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "/WEB-INF/jsp/systemmanage/city/cityList";
	}
	
	/**
	 * 打开“市信息管理”列表加载列表数据
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/systemmanage/city/queryCityListInfoDataGrid.json")
	public void queryCityListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {

		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);

			CityService cityService = (CityService) IssTransactionContainer.getInstance(CityService.class, false);
			long resultCount = cityService.findResultCount(map);
			List<City> resultList = cityService.findResultList(map);

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("citycode", DataTypeConstant.STRING);
			dataStyle.addDepict("cityname", DataTypeConstant.STRING);
			dataStyle.addDepict("provincename", DataTypeConstant.STRING);
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转省信息添加页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/city/toAddCity.web")
	public String toAddCity(HttpServletRequest request, HttpServletResponse response, Model model) {
		try{
			ProvinceService provinceService = (ProvinceService) IssTransactionContainer.getInstance(ProvinceService.class, false);
			List<Province> list = provinceService.queryProvince();
			model.addAttribute("list", list);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return "/WEB-INF/jsp/systemmanage/city/cityAdd";
	}
	
	/**
	 * 新增省信息
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/city/addCity.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addCity(HttpServletRequest request, HttpServletResponse response, Model model) {
		City city = null;
		try {
			city = (City) ServletUtils.getParametersToBaseEntity(request, City.class);
			city.setInputtime(new Date());
			city.setInputuserid(userContext.getLoginUser().getId());
			city.setModifytime(new Date());
			city.setModifyuserid(userContext.getLoginUser().getId());
			city.setStatusid(SysConstant.RecordStatus.VALID);
			CityService cityService = (CityService) IssTransactionContainer.getInstance(CityService.class, true);
			
			cityService.add(city);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/city/cityAdd";
	}
	
	@RequestMapping(value = "/systemmanage/city/validattionCity.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void validattionCity(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			City city = null;
			StringBuffer errorMsg = new StringBuffer();
			HashMap<String, Object> map = new HashMap<String, Object>();
			city = (City) ServletUtils.getParametersToBaseEntity(request, City.class);
			
			CityService cityService = (CityService) IssTransactionContainer.getInstance(CityService.class, false);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			if(null != city.getId()){
				map.put("id", city.getId());
			}
			map.put("citycode", city.getCitycode());
			if(!cityService.validationCity(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.city.cityAdd.aleert2")+"！\n");
			}
			map.remove("citycode");
			map.put("cityname", city.getCityname());
			if(!cityService.validationCity(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.city.cityAdd.aleert1")+"！\n");
			}
			map.remove("cityname");
			
			//判断用户选择的省是否正确
			if(city.getProvinceid() == null){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.province.provinceList.alert2"));
			}else{
				map.put("provinceid", city.getProvinceid());
				if(cityService.validationProvince(map)){
					errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmanage.province.provinceList.alert2"));
				}
				map.remove("provinceid");
			}
			
			if(StringUtils.isNotEmpty(errorMsg.toString())){
				userContext.setErrorMessage(errorMsg.toString());
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转修改市信息页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/city/toUpdateCity.web")
	public String toUpdateCity(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String cityId = getRequest().getParameter("id");
			CityService cityService = (CityService) IssTransactionContainer.getInstance(CityService.class, false);
			City city = cityService.findCityById(cityId);
			
			ProvinceService provinceService = (ProvinceService) IssTransactionContainer.getInstance(ProvinceService.class, false);
			List<Province> list = provinceService.queryProvince();
			
			model.addAttribute("list", list);
			model.addAttribute("city", city);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/city/cityUpdate";
	}
	
	/**
	 * 修改市信息
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/city/updateCity.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateCity(HttpServletRequest request, HttpServletResponse response, Model model) {
		City city = null;
		try {
			city = (City) ServletUtils.getParametersToBaseEntity(request, City.class);
			city.setModifytime(new Date());
			CityService cityService = (CityService) IssTransactionContainer.getInstance(CityService.class, true);
			cityService.update(city);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/city/cityList";
	}
	
	/**
	 * 删除市信息
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmanage/city/deleteCity.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteProvince(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Long cityId = Long.valueOf(getRequest().getParameter("id"));
			City city = new City();
			city.setId(cityId);
			city.setStatusid(SysConstant.RecordStatus.INVALID);
			CityService cityService = (CityService) IssTransactionContainer.getInstance(CityService.class, false);
			cityService.update(city);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
